package models

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"os"
	"time"
)

var MysqlDb *sql.DB
var MysqlDbErr error

var (
	USER = "root"
	PWD = "xiodi.cn123"
	HOST = "127.0.0.1"
	PORT = "3306"
	DB = "demo"
	CHARSET = "utf8mb4"
)

type User struct {
	Id int64 `db:"id"`
	Name string `db:"name"`
	Age int `db:"age"`
}

func GetEnv() {
	user := os.Getenv("MYSQL_USER")
	pwd := os.Getenv("MYSQL_PWD")
	host := os.Getenv("MYSQL_HOST")
	port := os.Getenv("MYSQL_PORT")
	db := os.Getenv("MYSQL_DB")
	fmt.Printf("test" + db)
	if len(user) != 0 {
		USER = user
	}
	if len(pwd) != 0 {
		PWD = pwd
	}
	if len(host) != 0 {
		HOST = host
	}
	if len(port) != 0 {
		PORT = port
	}
	if len(db) != 0 {
		DB = db
	}
}

func init() {
	GetEnv()
	fmt.Printf(DB)
	dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", USER, PWD, HOST, PORT, DB, CHARSET)
	MysqlDb, MysqlDbErr = sql.Open("mysql", dbDSN)
	if MysqlDbErr != nil {
		panic("数据库配置不正确：" + MysqlDbErr.Error())
	}

	MysqlDb.SetMaxOpenConns(100)         //最大连接数
	MysqlDb.SetConnMaxIdleTime(20)       //闲置连接数
	MysqlDb.SetConnMaxLifetime(100*time.Second)         //最大连接周期

	if MysqlDbErr = MysqlDb.Ping(); MysqlDbErr != nil {
		panic("数据库连接失败：" + MysqlDbErr.Error())
	}
}
